package com.example.dsplatform.Service.ipml;

import cn.hutool.core.util.RandomUtil;
import com.example.dsplatform.Dao.Mapper.MenuMapper;
import com.example.dsplatform.Dao.Mapper.UserMapper;
import com.example.dsplatform.Dao.Mapper.User_RoleMapper;
import com.example.dsplatform.Service.AdminService;
import com.example.dsplatform.Service.EmailService;
import com.example.dsplatform.pojo.Entity.Code;
import com.example.dsplatform.pojo.Entity.ResponseResult;
import com.example.dsplatform.utls.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Service
public class EmailServiceIpml implements EmailService {
    @Autowired
    JavaMailSender javaMailSender;
    @Autowired
    RedisCache redisCache;
    @Autowired
    UserMapper userMapper;
    @Override
    public ResponseResult sentEmailCode(String id,String email) {
        Code code = new Code();
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("hook3004@sina.com");
        code.setUid(id);
        code.setData(RandomUtil.randomNumbers(4));
        code.setEmail(email);
        message.setSubject("邮箱验证");
        message.setText("[学生管理系统]你的验证码为："+code.getData()+"，请妥善保管，切勿告诉外人");
        message.setTo(email);
        javaMailSender.send(message);
        redisCache.setCacheObject("Code:"+code.getData(), code,5, TimeUnit.MINUTES);
        return new ResponseResult(200, "验证码已发送");
    }

    @Override
    public ResponseResult loginByCode(String email,String code) {


        Code codeE = redisCache.getCacheObject("Code:"+code);
        if(Objects.isNull(codeE)){
            return new ResponseResult(204, "验证不通过");
        }
        else if (email.equals(codeE.getEmail()) && code.equals(codeE.getData())) {
            String id = codeE.getUid();
            userMapper.updateEmail(id,email);
            return new ResponseResult(200, "通过");


        }
        else  {
            return new ResponseResult(204, "验证不通过");
        }

    }
}